import * as Cesium from "cesium";

const buildingList = [
    {
        positions:[
            104.065552,30.572668,
            104.06634,30.572677,
            104.066308,30.5736,
            104.06552,30.57358
        ],
        title:"建筑1"
    },{
        positions:[
            104.066669,30.573564,
            104.066702,30.572699,
            104.06746,30.572708,
            104.067416,30.573583
        ],
        title:"建筑2"
    }
]
const buildingdefaultMaterial = Cesium.Color.fromRgba(0x00ff00).withAlpha(0.5);

const buildingActiveMaterial = Cesium.Color.fromRgba(0x0000ff).withAlpha(0.5);

function drawImage() {
    // create and draw an image using a canvas
    const canvas = document.createElement('canvas');
    const context2D = canvas.getContext('2d');
    // ... draw image
    return canvas;
}

export class XTMap{
    dom ?:HTMLElement;
    viewer ?: Cesium.Viewer;
    buildingEntities:any[]=[];

    activeBuilding ?:any;

    // 弹框
    popupDom ?:HTMLElement;

    private initMap(){
        if( !this.dom ) return false;

        Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxM2MxMTk5My04ZTUzLTRkZjktYjJlMy01ZTk0ZTg0NWNmOGUiLCJpZCI6MTMyMDc2LCJpYXQiOjE3MjQzOTU0OTd9.AzxL1b850PN2kS_1BNUNWJuig6vYgrRjBrXF1DMqwJU";

        this.viewer = new Cesium.Viewer(this.dom, {
            animation: false, //是否显示动画控件
            baseLayerPicker: false, //是否显示图层选择控件
            fullscreenButton: false, //是否显示全屏按钮
            geocoder: false, //是否显示地名查找控件
            timeline: false, //是否显示时间线控件
            homeButton: false,
            navigationHelpButton: false, //是否显示帮助信息控件
            sceneModePicker:false,
            infoBox:false,
        });

        // 加载高德影响
        const gaodeImageryProvider = new Cesium.UrlTemplateImageryProvider({
                url: 'https://webst02.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}',
                maximumLevel: 18,
                minimumLevel: 1,
                credit: 'Amap'
        });
        this.viewer.imageryLayers.removeAll();
        this.viewer.imageryLayers.addImageryProvider(gaodeImageryProvider);

        // 设置相机
        this.viewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(104.06698,30.565902, 1000),
            orientation:{
                pitch: Cesium.Math.toRadians(-50.0),
            }
        });
        this._renderBuilding();
        
        // 鼠标移入
        this.viewer.screenSpaceEventHandler.setInputAction((movement:any)=>{
            const pickedObject = this.viewer!.scene.pick(movement.endPosition);
            if (Cesium.defined(pickedObject)) {
                const building = this.buildingEntities.find((item)=>item === pickedObject.id);
                this._changeActiveBuilding(building);
            }else{
                this._changeActiveBuilding(null);
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // 点击事件
        let handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        handler.setInputAction((event:any)=>{
            const pickedObject = this.viewer!.scene.pick(event.position);
            if (Cesium.defined(pickedObject)) {
                const building = this.buildingEntities.find((item)=>item === pickedObject.id);
                console.log("点击了：",building);
            }else{
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    private _updatePosition(building:Cesium.Entity) {
        // 创建一个世界坐标
        var position = building.position?.getValue(Cesium.JulianDate.now())!;

        // 转换为屏幕坐标
        var screenCoordinate = Cesium.SceneTransforms.worldToWindowCoordinates(this.viewer!.scene, position)!;
        
        this.popupDom!.style.display = 'block';

        this.popupDom!.style.left = (screenCoordinate.x - (220 / 2)) + 'px';
        this.popupDom!.style.top = (screenCoordinate.y - 150) + 'px';
    }

    private _changeActiveBuilding(building:any){
        if( this.activeBuilding == building) return;
    
        this.buildingEntities.forEach((item)=>{
            item.polygon.material = buildingdefaultMaterial;
        });

        if( building ){
            building.polygon.material = buildingActiveMaterial;

            this.activeBuilding = building;
            this._updatePosition(building);
            // console.log(building);
        }else{
            this.activeBuilding = null;
            this.popupDom!.style.display = 'none';
        }
        
    }

    private _renderBuilding(){
        for(var i=0;i<buildingList.length;i++){
            const building = this.viewer?.entities.add({
                position: Cesium.Cartesian3.fromDegrees(buildingList[i].positions[0], buildingList[i].positions[1]),
                polygon:{
                    hierarchy: Cesium.Cartesian3.fromDegreesArray(buildingList[i].positions),
                    material: buildingdefaultMaterial,
                    extrudedHeight:200,
                    outline: true,
                    outlineColor: Cesium.Color.fromRgba(0xffff00).withAlpha(0.5),
                }
            });
            building?.polygon?.material.definitionChanged.addEventListener(()=>{
                this._changeActiveBuilding(building);
            });

            this.buildingEntities.push(building);
        }
        
    }

    init(dom:HTMLElement){
        this.dom = dom;

        // 弹框
        this.popupDom = document.getElementById('buildingInfo')!;

        this.initMap();
    }
}